<template>
  <div class="good-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入商品名称"
        style="width: 200px; margin-left:20px;"
      />
      <el-select v-model="searchForm.status" placeholder="商品状态" style="width: 200px; margin-left: 10px">
        <el-option label="全部" value="" />
        <el-option label="已上架" value="1" />
        <el-option label="已下架" value="0" />
      </el-select>
      <el-button type="primary" @click="searchGoods" style="margin-left: 10px">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="addGood" style="margin-left: auto;margin-right: 20px; ">新增商品</el-button>
    </div>

    <!-- 商品列表 -->
    <div class="goods-list">
    <el-table :data="pageGoodsList" style="margin-top: 20px">
      <el-table-column prop="good_id" label="商品ID" width="80" />
      <el-table-column label="商品信息" min-width="200">
        <template #default="scope">
          <div class="order-item">
            <el-image
              :src="scope.row.images"
              style="width: 50px; height: 50px"
            />
            <div class="item-info">
              <div>{{ scope.row.good_name }}</div>
              <div class="item-spec">{{ scope.row.description }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="style_name" label="款式" />
      <el-table-column prop="totalStock" label="总库存" />
      <el-table-column prop="status" label="审核状态">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
            {{ scope.row.status == 1 ? '已通过' : '未通过' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="is_on_shelf" label="上架状态">
        <template #default="scope">
          <el-tag :type="scope.row.is_on_shelf == 1 ? 'success' : 'info'">
            {{ scope.row.is_on_shelf == 1 ? '已上架' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="发布时间" width="110"/>
      <el-table-column label="操作" width="380">
        <template #default="scope">
          <el-button type="success" plain @click="editGood(scope.row)">编辑</el-button>
          <el-button type="info" plain @click="manageSku(scope.row.good_id, scope.row.good_name)">SKU管理</el-button>
          <el-button
            v-if="scope.row.status == 1" 
            :type="scope.row.is_on_shelf == 1 ? 'warning' : 'success'"
            @click="toggleStatus(scope.row.good_id, scope.row.is_on_shelf)"
            plain
          >
            {{ scope.row.is_on_shelf == 1 ? '下架' : '上架' }}
          </el-button>
          <el-button type="danger" plain @click="deleteGood(scope.row.good_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[3]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品新增弹窗 -->
    <el-dialog
      v-model="addGoodDialogVisible"
      :title="'新增商品'"
      width="600px"
    >
      <el-form :model="addingGood" label-width="100px">
        <el-form-item label="商品名称" required>
          <el-input v-model="addingGood.goodName" />
        </el-form-item>
        <el-form-item label="商品描述" required>
          <el-input v-model="addingGood.description" />
        </el-form-item>
        <el-form-item label="商品图片" required>
          <el-upload
            class="avatar-uploader"
            action='http://localhost:8081/taoxi/upload'
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAddingGoodSuccess"
            :on-error="handleAvatarError"
          > 
            <img v-if="addingGood.images" :src="addingGood.images" class="avatar" />
            <el-icon v-else><Plus /><p>上传</p></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品款式" required>
          <el-select v-model="addingGood.styleId" placeholder="请选择商品款式">
            <el-option 
              v-for="style in styleList" 
              :key="style.styleId" 
              :label="style.styleName" 
              :value="style.styleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" required>
          <el-input-number v-model="addingGood.price" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addGoodDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="AddGood">确定</el-button>
      </template>
    </el-dialog>

    <!-- 商品编辑弹窗 -->
    <el-dialog
      v-model="goodDialogVisible"
      :title="'编辑商品'"
      width="600px"
    >
      <el-form :model="editingGood" label-width="100px">
        <el-form-item label="商品名称" required>
          <el-input v-model="editingGood.goodName" />
        </el-form-item>
        <el-form-item label="商品描述" required>
          <el-input v-model="editingGood.description" />
        </el-form-item>
        <el-form-item label="商品图片" required>
          <el-upload
            class="avatar-uploader"
            action='http://localhost:8081/taoxi/upload'
            :headers="headers"
            :show-file-list="false"
            :on-success="handleEditingGoodSuccess"
            :on-error="handleAvatarError"
          >
            <img v-if="editingGood.images" :src="editingGood.images" class="avatar" />
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品价格" required>
          <el-input-number v-model="editingGood.price" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="goodDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGood">确定</el-button>
      </template>
    </el-dialog>

    <!-- SKU管理弹窗 -->
    <el-dialog
      v-model="skuDialogVisible"
      title="SKU管理"
      width="800px"
    >
      <div class="sku-header">
        <h3>{{ currentGood?.goodName }} - SKU列表</h3>
        <el-button type="primary" @click="addSku">新增SKU</el-button>
      </div>
      
      <el-table :data="currentSkuList" >
        <el-table-column prop="color" label="颜色" />
        <el-table-column prop="size" label="尺寸" />
        <el-table-column prop="quantity" label="库存" />
        <el-table-column label="图片">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary"  @click="editSku(scope.row)">编辑</el-button>
            <el-button  @click="deleteSku(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- SKU编辑弹窗 -->
    <el-dialog
      v-model="skuEditDialogVisible"
      :title="isEditSku ? '编辑SKU' : '新增SKU'"
      width="500px"
    >
      <el-form :model="editingSku" label-width="100px">
        <el-form-item label="颜色" required>
          <el-input v-model="editingSku.color" />
        </el-form-item>
        <el-form-item label="尺寸" required>
          <el-input v-model="editingSku.size" />
        </el-form-item>
        <el-form-item label="库存" required>
          <el-input-number v-model="editingSku.quantity" :min="0" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action='http://localhost:8081/taoxi/upload'
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
          >
            <img v-if="editingSku.image" :src="editingSku.image" class="avatar" />
            <el-icon v-else><Plus /><p>上传</p></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="skuEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSku(isEditSku)">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGoodsListAPI,addGoodAPI, editGoodAPI, deleteGoodAPI, getStyleListAPI, getSkuListAPI,addSkuAPI,updateSkuAPI,deleteSkuAPI } from '@/api/store'
import { useTokenStore } from '@/store/token'

// 获取登录用户信息
const tokenStore = useTokenStore();
const userId = tokenStore.user.userId;

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})
//分页
const total = ref(0); // 总条数
const pagePages = ref(1); // 总页数
const currentPage = ref(1); // 当前页码
const pageSize = ref(3);  // 每页显示条数
const pageGoodsList = ref([]); // 当前页的数据（用于显示）

// 更新分页数据（根据 currentPage 和 pageSize）
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pageGoodsList.value = goodsList.value.slice(start, end);  // 切割出当前页的数据
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

// 商品列表
const goodsList = ref([])

// 获取商品列表
function getGoodsList() {
  const userId = tokenStore.user.userId
  console.log(userId)
  getGoodsListAPI(userId).then(res => {
    console.log(res);
    
    if (res.code === 0) {
      goodsList.value = res.data
      const seenGoodIds = new Set();
      goodsList.value = goodsList.value.filter(good => {
        if (!seenGoodIds.has(good.good_id)) {
          seenGoodIds.add(good.good_id);
          return true;
        }
        return false;
      });
      total.value = goodsList.value.length
      pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
      updatePaginatedList();   // 更新分页数据
    } else {
      ElMessage.error(res.message)
    }
  })
}
getGoodsList();

// 配置请求头
const headers = {
  Authorization: encodeURIComponent(tokenStore.getToken())
}
// 处理头像上传成功
const handleAvatarSuccess = (res) => {
    if (res.code === 0) {
      editingSku.image = res.data
      ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}
const handleEditingGoodSuccess = (res) => {
    if (res.code === 0) {
      editingGood.images = res.data
      ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

const handleAddingGoodSuccess = (res) => {
    if (res.code === 0) {
      addingGood.images = res.data
      ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 上传失败回调
const handleAvatarError = (error) => {
  console.error('上传错误:', error)
  ElMessage.error('上传失败，请重试')
}

// 当前编辑的商品
const currentGood = ref({
  goodId: '',
  goodName: ''
})
// 商品编辑对象
const editingGood = reactive({
  goodId: '',
  goodName: '',
  price: 0,
  images: '',
  description: '',
})

// 新增商品对象
const addingGood = reactive({
  goodName: '',
  price: 0,
  images: '',
  description: '',
  styleId: ''
})

// 商品编辑对话框显示
const goodDialogVisible = ref(false)
// 商品新增对话框显示
const addGoodDialogVisible = ref(false)

// 搜索商品
const searchGoods = () => {
  // TODO: 调用接口搜索商品
  pageGoodsList.value = pageGoodsList.value.filter(item => {
    const matchesName = item.good_name.includes(searchForm.name);
    const matchesStatus = searchForm.status ? item.is_on_shelf === searchForm.status : true;
    return matchesName && matchesStatus;
  })
}
//重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  getGoodsList();
}

// 款式列表
const styleList = ref([])
// 新增商品相关方法
const addGood = () => {
  addGoodDialogVisible.value = true
  getStyleListAPI().then(res => {
    styleList.value = res.data
  })
}

const AddGood =() => {
  addGoodAPI(userId, addingGood).then(res => {
    if (res.code === 0) {
      ElMessage.success('添加成功')
      addGoodDialogVisible.value = false
    } else {
      ElMessage.error('添加失败')
    }
    getGoodsList();
  })
}

const editGood = (row) => {
  Object.assign(editingGood, { goodId: row.good_id, goodName: row.good_name, description: row.description, images: row.images, price: row.price })
  goodDialogVisible.value = true
}

const saveGood = () => {
  // TODO: 调用接口保存商品
  console.log(editingGood);
  
  editGoodAPI(editingGood).then(res => {
    if (res.code === 0) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(res.message || '保存失败')
    }
    getGoodsList();
  })
  goodDialogVisible.value = false
}

const toggleStatus = (good_id, is_on_shelf) => {
  ElMessageBox.confirm(`确定要${is_on_shelf == 1 ? '下架' : '上架'}该商品吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    // TODO: 调用接口修改状态
    if (is_on_shelf == 0) {
      is_on_shelf = '1'
    } else if (is_on_shelf == 1) {
      is_on_shelf = '0'
    }
    let data = {
      goodId: good_id,
      isOnShelf: is_on_shelf
    }
    editGoodAPI(data).then(res => {
      if (res.code === 0) {
        is_on_shelf = is_on_shelf == 1 ? 0 : 1
        ElMessage.success(`${is_on_shelf == 1 ? '下架' : '上架'}成功`)
      } else {
        ElMessage.error('修改失败')
      }
      getGoodsList();
    })
  })
}

const deleteGood = (good_id) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    type: 'warning'
  }).then(() => {
    // TODO: 调用接口删除商品
    let goodsId = good_id
    deleteGoodAPI(goodsId).then(res => {
      if (res.code === 0) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败')
      }
      getGoodsList();
    })
  })
}

// SKU管理
const skuList = ref([])
const currentSkuList = ref([])  // 当前商品SKU列表
const skuDialogVisible = ref(false)
const skuEditDialogVisible = ref(false)
const isEditSku = ref(false)
const editingSku = reactive({});

// TODO: 调用接口获取SKU列表
function getSkuList() {
  getSkuListAPI(userId).then(res => {
    if (res.code === 0) {
      skuList.value = res.data
      // 获取库存
      // 创建一个用于累加库存的字典
      const stockMap = {};
      // 遍历所有SKU，计算每个商品的总库存
      skuList.value.forEach(item => {
        if (stockMap[item.good_id]) {
          stockMap[item.good_id] += item.quantity;
        } else {
          stockMap[item.good_id] = item.quantity;
        }
      });

      // 为每个商品添加 totalStock 属性
      pageGoodsList.value.forEach(item => {
        item.totalStock = stockMap[item.good_id];
      });
      currentSkuList.value = skuList.value.filter(sku => sku.good_id === currentGood.value.goodId);
    } else {
      console.log('获取SKU列表失败，请重试' || res.message)
    }
  })
}
getSkuList();

// SKU相关方法
const manageSku = (good_id, good_name) => {
  currentGood.value.goodId = good_id;
  currentGood.value.goodName = good_name;
  console.log(currentGood.value);
  currentSkuList.value = skuList.value.filter(sku => sku.good_id === currentGood.value.goodId)
  console.log(currentSkuList.value);
  
  skuDialogVisible.value = true
}

const addSku = () => {
  isEditSku.value = false
  Object.assign(editingSku, {
    color: '',
    size: '',
    stock: 0,
    image: ''
  })
  skuEditDialogVisible.value = true
}

const editSku = (row) => {
  isEditSku.value = true
  Object.assign(editingSku, row)
  skuEditDialogVisible.value = true
}

const saveSku = (isEditSku) => {
  // TODO: 调用接口保存SKU
  // 新增SKU方法
  if (isEditSku === false) {
    console.log('新增SKU');
    let data = {goodId: currentGood.value.goodId, color: editingSku.color, size: editingSku.size, quantity: editingSku.quantity, image: editingSku.image}
    addSkuAPI(data).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增sku成功')
      } else {
        ElMessage.error('新增sku失败')
      }
      // 重新获取SKU列表
      getSkuList();
    })
  }
  // 编辑SKU方法
  if (isEditSku === true) {
    let data = {skuId: editingSku.sku_id, shopGoodsId: editingSku.shop_goods_id, color: editingSku.color, size: editingSku.size, quantity: editingSku.quantity, image: editingSku.image}
    console.log('编辑SKU ' + data);
    updateSkuAPI(data).then(res => {
      if (res.code === 0) {
        console.log(res);
        ElMessage.success('修改sku成功')
      } else {
        ElMessage.error('修改sku失败，请重试' || res.message)
      }
      // 重新获取SKU列表
      getSkuList();
    })
  }
  skuEditDialogVisible.value = false
}


const deleteSku = (row) => {
  ElMessageBox.confirm('确定要删除该SKU吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    // TODO: 调用接口删除SKU
    console.log(row.sku_id);
    let skuId = row.sku_id
    deleteSkuAPI(skuId).then(res => {
      if (res.code === 0) {
        ElMessage.success('删除sku成功')
      } else {
        ElMessage.error('删除sku失败')
      }
      // 重新获取SKU列表
      getSkuList();
    })
  })
}

</script>

<style scoped>
.order-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-info {
  margin-left: 10px;
  flex: 1;
}

.item-spec {
  color: #999;
  font-size: 12px;
  margin: 5px 0;
}

.item-price {
  color: #666;
}

.goods-list{
  position: relative;
  margin-top:20px;
}

.good-management {
  padding: 20px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.search-bar {
  display: flex;
  align-items: center;
  background: #fff;
  height: 80px;
}

.sku-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  position: absolute;
  margin-top: 20px;
  margin-left: 20%;
  display: flex;
  justify-content: flex-end;
  bottom: 20px;
}
</style>